//
//  SearchViewController.m
//  UGoods
//
//  Created by dllo on 16/1/26.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "SearchViewController.h"
#import "BaseTableView.h"
#import "LHAFNetworkTool.h"
#import "FindModel.h"
#import "SSAutoresizeLabelFlow.h"
#import "SSAutoresizeLabelFlowConfig.h"
#import "BaseCollectionView.h"
#import "TagCollectionViewCell.h"
#import "SearchAfterViewController.h"
#import "ConstantsDefine.h"
#import "BuyDetailViewController.h"
@interface SearchViewController ()<UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) UISearchBar *searchBar; /**< 搜索框 */
@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) NSArray *dataArray;
@property (nonatomic, retain) NSMutableArray *searchDataArray;
@property (nonatomic, retain) UICollectionView *collectionView;



@end

@implementation SearchViewController

- (void)dealloc
{
    [_searchBar release];
    [_tableView release];
    [_dataArray release];
    [_collectionView release];
    [super dealloc];
}

// 创建searchBar
- (void)createSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200 * WIDTH, 30 * HEIGHT)];
    _searchBar.placeholder = @"搜索类别，品牌，原产地";
    _searchBar.barStyle = UIBarStyleBlack;
    _searchBar.delegate = self;
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    self.navigationItem.titleView = _searchBar;
    [_searchBar release];
    
}

// 开始编辑状态
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    return YES;
}

// 结束编辑状态
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    
    return YES;
}

// 输入文本时方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSString *str = [NSString stringWithFormat:@"http://api.ujipin.com/v2/app/ios/phone/v3/keywords/getLikeKeywordsList?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=320&keywords=%@", searchText];
    self.searchDataArray = [NSMutableArray array];
    
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"data"];
        self.searchDataArray = [NSMutableArray arrayWithArray:array];
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    /* 搜索关键字高亮 */
    NSMutableAttributedString *AttributedString = [[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", self.searchDataArray[indexPath.row]]] autorelease];
    NSRange range = [[NSString stringWithFormat:@"%@", self.searchDataArray[indexPath.row]] rangeOfString:self.searchBar.text];
    [AttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.textLabel.attributedText = AttributedString;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchAfterViewController *afrer = [[SearchAfterViewController alloc] init];
    afrer.searchText = _searchDataArray[indexPath.row];
    [self.navigationController pushViewController:afrer animated:YES];
    [afrer release];
}

// searchBar点击事件
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    SearchAfterViewController *afrer = [[SearchAfterViewController alloc] init];
    afrer.searchText = searchBar.text;
    [self.navigationController pushViewController:afrer animated:YES];
    [afrer release];
    NSLog(@"%@", searchBar.text);
}

- (void)handleData {
    NSString *str = @"http://api.ujipin.com/v2/app/ios/phone/v3/keywords/getHotKeywordsList?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314";
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        self.dataArray = [NSArray arrayWithArray:resposeObject[@"data"][@"data"]];
        
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

//创建CollectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(10 * HEIGHT, 10 * WIDTH, 10 * HEIGHT, 10 * WIDTH);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10 * WIDTH, 74 * HEIGHT, self.view.frame.size.width - 20 * WIDTH, self.view.frame.size.height / 2) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
//    [self.view addSubview:_collectionView];
    self.tableView.tableFooterView = self.collectionView;
    [_collectionView release];
    [_collectionView registerClass:[TagCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}

// 设定cell尺寸的协议方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = _dataArray[indexPath.item];
    CGFloat w = [TagCollectionViewCell widthWithText:str];
    CGSize rect = CGSizeMake(w * WIDTH + 10 * WIDTH, 20 * HEIGHT);
    return rect;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TagCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.tagLabel.text = _dataArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *str = _dataArray[indexPath.item];
    SearchAfterViewController *afrer = [[SearchAfterViewController alloc] init];
    afrer.searchText = str;
    [self.navigationController pushViewController:afrer animated:YES];
    [afrer release];
    NSLog(@"%@", str);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self handleData];
    [self createSearchBar];
    [self createTableView];
    [self createCollectionView];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
